<?php
/**
 * 用于微信被动回复消息回调页面的方法集
 * Created by PhpStorm.
 * User: sh01
 * Date: 2018/1/9
 * Time: 9:26
 */

namespace corpWeixin;
use bobchengbin\Yii2XmlRequestParser\Xml2Array;
use corpWeixin\corpWeixinSdk\CWXTool;

class CWXCallBack
{

    /**
     * 初次配置企业微信回调URL校验
     * @param $GetData
     * @return bool|string
     */
    public function verifyUrl($GetData)
    {
        /* @var $cwxTool \corpWeixin\corpWeixinSdk\CWXTool*/
        $cwxTool = CWXTool::getInstance();
        $echostr = urldecode($GetData["echostr"]);
        $msg_signature = urldecode($GetData["msg_signature"]);
        $timestamp = urldecode($GetData["timestamp"]);
        $nonce = urldecode($GetData["nonce"]);
        $replyEchoStr = '';
        $res = $cwxTool->crypt->VerifyURL($msg_signature,$timestamp,$nonce,$echostr,$replyEchoStr);
        return $res===0?$replyEchoStr:false;
    }

    /**
     * 企业微信接收消息回调验证解密并返回消息
     * @param $getData
     * @param $postData
     * @return array|bool
     */
    public function decryptMsg($getData,$postData)
    {
        /* @var $cwxTool \corpWeixin\corpWeixinSdk\CWXTool*/
        $cwxTool = CWXTool::getInstance();
        $msg_signature = $getData['msg_signature'];
        $timestamp = $getData['timestamp'];
        $nonce = $getData['nonce'];
        $msgXml = '';
        $res = $cwxTool->crypt->DecryptMsg($msg_signature,$timestamp,$nonce,$postData,$msgXml);
        if($res === 0 && $msg2Arr = Xml2Array::go($msgXml))
        {
            return $msg2Arr['xml'];
        }
        return false;
    }

    /**
     * 生成待发送的xml消息（直接echo，或许再加个head头声明文档格式）
     * @param $fromUser
     * @param $toUser
     * @param $replyMsg
     * @return bool|string
     */
    public function encryptMsg($fromUser,$toUser,$replyMsg)
    {
        /* @var $cwxTool \corpWeixin\corpWeixinSdk\CWXTool*/
        $cwxTool = CWXTool::getInstance();
        $encryptMsg = '';
        $replyMsg = $cwxTool->xmlMessage($fromUser,$toUser,$replyMsg);
        $nonce = (string)mt_rand(100000,999999);
        $res = $cwxTool->crypt->EncryptMsg($replyMsg, time(), $nonce, $encryptMsg);
        if($res === 0 )
            return $encryptMsg;
        return false;

    }
}